﻿using NHibernate;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Water.Data.Infrastructure;

namespace Water.Data.Repositories
{
    public class GetNumberRepository : NhRepositoryBase<Hashtable>
    {

        public GetNumberRepository(ISession session)
            : base(session)
        {
        }

        public string GetNumber(string tableName, string columnName = "MRNO", string orderdesc = "CreateDt")
        {
            try
            {
                string queryStr = "select top 1 " + columnName + " as Number from " + tableName + " order by " + orderdesc +" desc";
                IQuery query = session.CreateSQLQuery(queryStr);
                var listResult = query.SetResultTransformer(NHibernate.Transform.Transformers.AliasToEntityMap).List<Hashtable>();
                string maxNo = null;
                if (listResult != null && listResult.Count>0)
                {
                    maxNo = listResult[0]["Number"].ToString();
                }
                //20130620001
                // var mr = GetMany(e => true).OrderByDescending(e => e.CreateDt).Take(1).SingleOrDefault();
                //  string maxNo = mr == null ? null : mr.MRNO;
                // mr.MRNO = maxNo;
                if (!string.IsNullOrEmpty(maxNo))
                {
                    //string maxNo = mr.MRNO;
                    DateTime dt = DateTime.ParseExact(maxNo.Substring(0, 8), "yyyyMMdd", null);
                    DateTime dtnow = DateTime.Today;
                    if (dtnow == dt)
                    {
                        string num = maxNo.Substring(8);
                        int inum = Convert.ToInt32(num) + 1;
                        num = inum.ToString().PadLeft(3, '0');
                        return DateTime.Now.ToString("yyyyMMdd") + num;
                    }
                    else
                    {
                        return DateTime.Now.ToString("yyyyMMdd") + "001";
                    }
                }
                else
                {
                    return DateTime.Now.ToString("yyyyMMdd") + "001";
                }
            }
            catch
            {

                return string.Empty;
            }
        }
    }
}
